package com.example.springboot.util;

import com.example.springboot.model.Email;
import com.example.springboot.model.EmailExample;

import javax.mail.Message;
import javax.mail.Part;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 用于获取邮箱中邮件信息的线程
 * @author lupf
 *
 */
public class GetMailInfoThread extends Thread {

    Message message[];
    MailImfo re = null;
    public GetMailInfoThread(Message message[])
    {
        this.message = message;
    }

    /**
     * 存数据库
     * @param re
     */
    private void saveEmail( MailImfo re ){
        try{
            //避免重复数据
            EmailExample example =new EmailExample();
            example.createCriteria().andMessageIdEqualTo(re.getMessageId());
            List<Email> es =ApplicationContextMine.getEmailMapper().selectByExample(example);
            if(es.size()>0)return;
            Email e=new Email();
            e.setType(1);//设置邮件类型
            e.setTitle( re.getSubject());
            e.setIsNeedReplay(re.getReplySign());
            e.setIsRead(re.isNew());
            e.setEmailContent(re.getBodyText());
            e.setSendAddr(re.getFrom());
            e.setReviceAddr(re.getMailAddress("to"));
            e.setSendTime(re.getSentDate());
            e.setMessageId(re.getMessageId());
            ApplicationContextMine.getEmailMapper().insert(e);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    @Override
    public void run()
    {

        super.run();
        if (null != message)
        {
            for (int i = 0; i < message.length; i++)
            {
                try
                {
                    re = new MailImfo((MimeMessage) message[i]);
                    re.getMailContent((Part) message[i]);
                    saveEmail(re);
//                    System.out.println("邮件　" + i + "　是否包含附件:　" + re.isContainAttach((Part) message[i]));
//                    System.out.println("邮件　" + i + "　抄送:　" + re.getMailAddress("cc"));
//                    System.out.println("邮件　" + i + "　暗抄:　" + re.getMailAddress("bcc"));
//                    System.out.println("邮件　" + i + "　邮件ID:　" + re.getMessageId());
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
        }
    }
}